var Watchlist_StartUpManager = function(){
    this.startups = {};
    this.randomId = 0;
};
Watchlist_StartUpManager.prototype = {
    reg : function(startupObj){
        startupObj.__id = ++this.randomId;
        this.startups[startupObj.__id] = startupObj;
    },
    sync: function(startupObj){
        for(var s in this.startups){
            if(this.startups[s] && this.startups[s]._refreshList && (typeof startupObj=='undefined'||startupObj.__id != this.startups[s].__id)){
                this.startups[s]._refreshList();
            }
        }
    }
};
var QS_WatchlistStartUpManager = new Watchlist_StartUpManager();

var Watchlist_StartUp = function(container, config, callbacks){
    this.container = container[0] ? container : $(container);
    this.config = $.extend(true, {
        contextMenu: true,
        contextMenuContainer: this.container
    }, config);
    this.el = null;
    this.grid = null;
    this.data = [];
    this.height = 0;
    this._isShow = true;
    this.selectedRow = null;
    this.ddlTypeDataMap = {};
    this.ready = false; //
    this.init();
    this.onExcute = null;
    this.selectedInfo = {};
    
}
Watchlist_StartUp.prototype = {
	_getHTML:function(){
		var qslan=QS_Lang.watchlist;
        return '<div class="wl-startup"><div class="wl-startup-hd"><h4>'+qslan["prompttxt"]+'</h4>'
              + '<div class="filter clearfix"><a class="qs-ui-btn btn-new" href="#">'+qslan["new"]+'</a></div></div>'
              + '<div class="grid"></div></div>';
    },
    init: function(){
        var self = this,qslan=QS_Lang.watchlist;
        this.el = $(this._getHTML()).appendTo(this.container);
        this.hd = this.el.find('.wl-startup-hd');
        this.filterEl = this.el.find('div.filter');
        
        this.btnNew = this.el.find('a.btn-new').mouseover(function(e){
            self.newBtnMenu.show();
        }).mouseout(function(e){
            self.newBtnMenu.hide(100);
        });
        var importSubMenu = [];
        if(GOLBAL_DATA.SSOFrom.toLowerCase()=="office"){
            importSubMenu.push({
                txt: qslan["office"],
                val: 'import_office'
            });
        }
        if(GOLBAL_DATA.SSOFrom.toLowerCase()=="direct"){
            importSubMenu.push({
                txt: qslan["direct"],
                val: 'import_direct'
            });
        }
        importSubMenu.push({
            txt: qslan["c&p"],
            val: 'import_manual'
        },{
            txt: qslan["upload"],
            val: 'excel'
        });

        this.newBtnMenu = new Util.CascadeMenu(this.filterEl, {
            display: false,
            autoHide: true
        }, [{
            txt: qslan["wl"],
            val: 'new_wl'
        },  {
            txt: qslan["pl"],
            val: 'new_pl'
        }, importSubMenu.length > 0 ? {
            txt: qslan["import"],
            val: '',
            subMenu: importSubMenu
        } : null], {
            onClick: function(item){
                self.onNewButtonExcute(item.data.val);
            }
        });
        this.contentMenu = new Util.CascadeMenu(this.config.contextMenuContainer, {
            display: false,
            isTraceMouse: true,
            autoHide: true,
			menuContainment:"document",
            fixedDirection: false
        }, [{
            txt: qslan["open"],
            val: 'open',
            subMenu: [{
                txt: qslan["curtab"],
                val: 'open'
            }, {
                txt: qslan["newtab"],
                val: 'open_tab'
            }, typeof QS_Detaching == 'undifined' ? null : {
                txt: qslan["newwin"],
                val: 'open_win'
            }]
        },{
			txt: qslan["rename"],
			val: 'rename'
		},{
            txt: qslan["edit"],
            val: 'edit'
        },{
            txt: qslan["delete"],
            val: 'del'
        }], {
            onClick: function(item){
				self.onContextMenuExcute(item.data.val);
            }
        });
        
        this._createGrid();
        this.ddlType = new Util.DropDownList(this.filterEl, function(t, v){
            self.grid.reBindData(self._filterData());
        }, [{
            txt: qslan["type_anytype"],
            val: ''
        },{
            txt: qslan["type_list"],
            val: 'List'
        }, {
            txt: qslan["type_portfolio"],
            val: 'Portfolio'
        }], {
            width: 80
        });
        this.ddlOwner = new Util.DropDownList(this.filterEl, function(t, v){
            self.grid.reBindData(self._filterData());
        }, [{
            txt: qslan["owner_anyowner"],
            val: ''
        }, {
            txt: qslan["owner_me"],
            val: 'Me'
        }, {
            txt: qslan["owner_mroningstar"],
            val: 'Morningstar'
        }], {
            width: 80
        });
        
        QS_WatchlistStartUpManager.reg(this);
    },
	onContextMenuExcute:function(type){
		var self = this;
		this.onExcute(type,this.selectedRow,function(cbType,cbData){
			if(cbType=="del"){
                if (cbData) {
                    self.grid.removeRow(self.selectedRow.id);
                } else {
                    Util.alert(QS_Lang.text["watchlistdeleteerror"]);
                }
			}
		});
	},
	onNewButtonExcute:function(type){
        var self = this;
        this.onExcute(type,{type:type},function(cbType,cbData){
            if (cbType == "new_wl") {
                if (cbData.length > 0) {
                    self.hide();
                }
            }
        });
		
    },
    rebindTypeDDL:function(){
        var data = [{
            txt: QS_Lang.watchlist["type_anytype"],
            val: ''
        }];
        for(var t in this.ddlTypeDataMap){
            data.push({
                txt: t,
                val: t
            });
        }
        this.ddlType.rebindData(data);
    },
    _filterData: function(type, owner){
        var _data = [];
        type = type || this.ddlType ? this.ddlType.getValue() : '';
        owner = owner || this.ddlOwner ? this.ddlOwner.getValue() : '';
        
        var _filter = function(data, field, value){
            var _d = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i][field] == value || value == '') {
                    _d.push(data[i]);
                    continue;
                }
            }
            return _d;
        };
        
        return _filter(_filter(this.data, 'typeTxt', type), 'owner', owner);
        
    },
    createList: function(o){
        var lst = o.Portfolios;
        this.data = [];
        if (o && o.Portfolios) {
            for (var i = 0; i < lst.length; i++) {
				if(lst[i].Source=="temp"){
					continue;
				}
                this.data.push({
                    name: lst[i].Name,
                    id: lst[i].PfId,
                    type: lst[i].Type,
                    typeTxt: lst[i].TypeTxt,
                    owner: lst[i].Owner,
                    permission: lst[i].Permission,
                    date: lst[i].UpdateTime
                });
                this.ddlTypeDataMap[lst[i].TypeTxt] = true;
            }
        }
        //this.grid.reBindData(this.data);
        this.grid.reBindData(this._filterData());
        this.rebindTypeDDL();
		this.ready=true;
    },
    _refreshList:function(){
        var self = this;
        QS_watchlistDataManager.getPortfolioList(function(plist){
            self.createList({
                Portfolios: plist
            });
        });
    },
    refreshList: function(){
        this._refreshList();
        //QS_WatchlistStartUpManager.sync(this);
    },
    _createGrid: function(){
        var self = this,qslan=QS_Lang.watchlist;
        this.grid = new Util.DataGrid(this.el.find('div.grid'), {}, {
            column: [{
                header: "id",
                dataIndex: 'id',
                dataType: 'int',
                hide: true,
                width:'0'
            },{
                header: qslan["name"],
                dataIndex: 'name',
                dataType: 'string',
                width:'35%'
            }, {
                header: "Type",
                dataIndex: 'type',
                width:'0',
                hide: true
            }, {
                header: qslan["typetxt"],
                dataIndex: 'typeTxt',
                width:'20%'
            }, {
                header: qslan["owner"],
                dataIndex: 'owner',
                width:'20%'
            }, {
                header: qslan["permission"],
                dataIndex: 'permission',
                width:'20%'
            }, {
                header: qslan["date"],
                dataIndex: 'date',
                width:'20%',
                hide:true
            }, {
                dataIndex: 'del',
                renderer: '<a class="btn-del">Remove</a>',
                width: '5%'
            }],
            indexColKey: 'id',
            height: this.container.height() - this._getGirdHeightOffset(),
            autoWidth: true,
            rowLayout: 'list',
            rowDragable: false,
            rowDropable: false,
            rowInvertSelect:false
        }, {
            onRowSelected:function(e, row){
				self.selectedRow = {
                    id: row.id,
                    type: row.data.type,
                    name: row.cells['name'].text
                };
                if (e && $(e.target).hasClass('btn-del')) {
                   self.onContextMenuExcute("del");
                }
                else {
                   self.onContextMenuExcute("open");
                }
            },
            onRowContextmenu: function(e, row){
                self.selectedRow = {
                    id: row.id,
                    type: row.data.type,
                    name: row.cells['name'].text
                };
                if(row.cells['permission'].text == 'Read Only'){
                    self.contentMenu.disableItem('edit');
                    self.contentMenu.disableItem('del');
					self.contentMenu.disableItem('rename');
                }else{
                    self.contentMenu.enableItem('edit');
                    self.contentMenu.enableItem('del');
					self.contentMenu.enableItem('rename');
                }
                self.contentMenu.show(e);
            }
        });
    },
    _getGirdHeightOffset:function(){
        return this.hd.height()+6;
    },
    resize:function(w, h){
        this.height = h;
        this.grid.resize('auto', h-this._getGirdHeightOffset());
    },
    show:function(){
        if(!this._isShow){
            this._isShow = true;   
            this.el.show();
            this.grid.resize('auto', this.height-this._getGirdHeightOffset());
        }      
    },
    hide:function(removeTab){
        if (this._isShow) {
            this.el.hide();
            this._isShow = false;
        } 
    }
};
